package com.jier.common.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * 控制器增强
 *
 * @author jie_r
 * @date 2016/8/30
 */
@EnableWebMvc
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<ErrorMessage> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        System.out.println("参数解析失败");
        return new ResponseEntity<ErrorMessage>(new ErrorMessage(e.getMessage()), HttpStatus.BAD_REQUEST);
    }

    /**
     * 403 - Bad Request
     */
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(HttpParamException.class)
    public ResponseEntity<ErrorMessage> forbiddenException(HttpParamException e) {
        System.out.println("参数验证失败：" + e.getMessage());
        return new ResponseEntity<ErrorMessage>(new ErrorMessage(e.getMessage()), HttpStatus.FORBIDDEN);
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<ErrorMessage> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        System.out.println("不支持当前请求方法：" + e.getMessage());
        return new ResponseEntity<ErrorMessage>(new ErrorMessage("不支持当前请求方法"), HttpStatus.METHOD_NOT_ALLOWED);
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ErrorMessage> handleException(RuntimeException e) {
        System.out.println(e.getMessage());
        return new ResponseEntity<ErrorMessage>(new ErrorMessage("服务运行异常"), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
